/**
 * @file     getIntersectionNode.ts
 * @brief    [160. 相交链表](https://leetcode.cn/problems/intersection-of-two-linked-lists/)
 * @author   Zhu
 * @date     2022-10-30 20:37
 */
import { ListNode } from '../helper';

function getIntersectionNode(
    headA: ListNode | null,
    headB: ListNode | null
): ListNode | null {
    if (!headA || !headB) return null;
    let a: ListNode | null = headA,
        b: ListNode | null = headB;

    while (a !== b) {
        a = a == null ? headB : a.next;
        b = b == null ? headA : b.next;
    }

    return a;
}

// 辅助理解过程
function getIntersectionNode(
    headA: ListNode | null,
    headB: ListNode | null
): ListNode | null {
    if (!headA || !headB) return null;
    let a = headA;
    let b = headB;

    let aChanged = false;
    let bChanged = false;

    while (a || b) {
        if (a === b) return a;
        if (a.next) {
            a = a.next;
        } else {
            if (aChanged) return null;
            aChanged = true;
            a = headB;
        }
        if (b.next) {
            b = b.next;
        } else {
            if (bChanged) return null;
            bChanged = true;
            b = headA;
        }
    }

    return null;
}
